package com.mav01.mrpbackend.controller;

import com.mav01.mrpbackend.mapper.MrpPlanMapper;
import com.mav01.mrpbackend.pojo.*;
import com.mav01.mrpbackend.service.MrpCalculationService;
import com.mav01.mrpbackend.service.MrpProductsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/mrp")
public class MrpController {

    @Autowired
    private MrpCalculationService mrpCalculationService;

    @Autowired
    private MrpPlanMapper mrpPlanMapper;

    @Autowired
    private MrpProductsService mrpProductsService;

    /**
     * 获取产品名称列表
     */
    @GetMapping("/products")
    public Result<List<Material>> getProductNames() {
        return Result.success(mrpProductsService.getProductNames());
    }


    /**
     * 创建MRP计划并计算
     */
    @PostMapping("/calculate")
    public Result<MrpPlanVO> calculateMrp(@RequestBody MrpPlanRequest request) {
        try {
            MrpPlan plan = mrpCalculationService.calculateMrp(request);
            // 将结果转换为VO
            MrpPlanVO planVO = new MrpPlanVO();
            BeanUtils.copyProperties(plan, planVO);
            List<MrpResult> results = plan.getResults();
            List<MrpResultVO> resultsVO = new ArrayList<>();
            // 遍历每个元素并拷贝属性
            for (MrpResult result : results) {
                MrpResultVO resultVO = new MrpResultVO();
                BeanUtils.copyProperties(result, resultVO);
                resultsVO.add(resultVO);
            }
            planVO.setResults(resultsVO);
            //返回前端数据
            return Result.success(planVO);
        } catch (Exception e) {
            return Result.error("MRP计算失败: " + e.getMessage());
        }
    }

    /**
     * 根据计划ID查询MRP计划
     */
    @GetMapping("/plan/{planId}")
    public Result<MrpPlan> getMrpPlan(@PathVariable Long planId) {
        MrpPlan plan = mrpPlanMapper.selectMrpPlanById(planId);
        if (plan == null) {
            return Result.error("计划不存在");
        }

        List<MrpResult> results = mrpPlanMapper.selectMrpResultsByPlanId(planId);
        plan.setResults(results);

        return Result.success(plan);
    }

    /**
     * 获取所有MRP计划
     */
    @GetMapping("/plans")
    public Result<List<MrpPlan>> getAllMrpPlans() {
        // 这里需要实现查询所有计划的逻辑
        return Result.success(Collections.emptyList());
    }
}
